package com.ihome.excel.xlsx.engine.imports;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import com.ihome.excel.xlsx.entity.TemplateConfig;
import com.ihome.excel.xlsx.exceptions.ThrowableDefine;
import com.ihome.excel.xlsx.validate.ICellsValidateRule;

@SuppressWarnings("all")
public class RowParseEngine {

	private CellParseEngine cellParse = new CellParseEngine();
	
	private static final String SET = "set";
	
	public Map getRowValueMap(Row row, TemplateConfig config, ICellsValidateRule validateRule) {
		int totalColumns = row.getLastCellNum();
		Map rowMap = new HashMap<>();
		Cell cell;
		for (int cellnum = 0; cellnum < totalColumns; cellnum++) {
			cell = row.getCell(cellnum);
			rowMap.put(config.getAttributeConfig().get(String.valueOf(cellnum)).getField(),
					cellParse.getCellValue(cell, validateRule.getValidateRule().get(String.valueOf(cellnum))));
		}
		return rowMap;
	}

	public Object getRowValueEntity(Row row, Class classa, TemplateConfig config, ICellsValidateRule validateRule) {
		int totalColumns = row.getLastCellNum();
		Object entity;
		Cell cell;
		String fieldName;
		String methodName;
		Method[] methods = null;
		try {
			entity = classa.newInstance();
			methods = entity.getClass().getDeclaredMethods();
		} catch (InstantiationException e) {
			throw ThrowableDefine.SHEET_CLASSA_REFLECTION_ERROR.getSheetValidateException(e.getMessage());
		} catch (IllegalAccessException e) {
			throw ThrowableDefine.SHEET_CLASSA_REFLECTION_ERROR.getSheetValidateException(e.getMessage());
		}
		for (int cellnum = 0; cellnum < totalColumns; cellnum++) {
			cell = row.getCell(cellnum);
			fieldName = config.getAttributeConfig().get(String.valueOf(cellnum)).getField();
			methodName = SET + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1, fieldName.length());
			for (Method md : methods) {
				if (methodName.equals(md.getName())) {
					try {
						md.invoke(entity, cellParse.getCellValue(cell,
								validateRule.getValidateRule().get(String.valueOf(cellnum))));
					} catch (IllegalAccessException e) {
						throw ThrowableDefine.SHEET_CLASSA_REFLECTION_ERROR.getSheetValidateException(e.getMessage());
					} catch (IllegalArgumentException e) {
						throw ThrowableDefine.SHEET_CLASSA_REFLECTION_ERROR.getSheetValidateException(e.getMessage());
					} catch (InvocationTargetException e) {
						throw ThrowableDefine.SHEET_CLASSA_REFLECTION_ERROR.getSheetValidateException(e.getMessage());
					}
				}
			}
		}
		return entity;
	}

}
